const Diff = require('diff')
import _ from 'lodash'
export const randWord = (arr) => {
  // console.log(arr)
  let newArr = [];
  for(let i=0; i<arr.length; i++){
    let index = Math.floor(Math.random()*arr.length);// 随机下标
    newArr.push(arr[index]);// 将随机出的元素，存放新数组newArr中去
    arr.splice(index,1); // 将随机出的元素在arr中删除            
  }
// arr中删除随机出的元素,arr.length-1,同时i++,导致循环不会10次,会是5次.最后得到newArr中只有一半的随机数字,arr中剩下另一半. 将其合并到一起,得到res
  let res =[...newArr,...arr];
  return res
}

const strSimilarity2Number = (s, t) => {
  var n = s.length, m = t.length, d = [];
  var i, j, s_i, t_j, cost;
  if (n == 0) return m;
  if (m == 0) return n;
  console.log(t.length)
  for (i = 0; i <= n; i++) {
      d[i] = [];
      d[i][0] = i;
  }
  for (j = 0; j <= m; j++) {
      d[0][j] = j;
  }
  for (i = 1; i <= n; i++) {
      s_i = s.charAt(i - 1);
      for (j = 1; j <= m; j++) {
          t_j = t.charAt(j - 1);
          if (s_i == t_j) {
              cost = 0;
          } else {
              cost = 1;
          }
          d[i][j] = Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
      }
  }
  return d[n][m];
}

const Minimum = (a, b, c) => {
  return a < b ? (a < c ? a : c) : (b < c ? b : c);
}

//两个字符串的相似程度，并返回相似度百分比
export const zhSimilarity2Percent = (s, t) => {
  var l = s.length > t.length ? s.length : t.length;
  var d = strSimilarity2Number(s, t);
  return (1 - d / l).toFixed(4);
}
export const strSimilarity2Percent = (s, t) => {
  return Cosinesimilarity(s, t) / 100
  // var l = s.length > t.length ? s.length : t.length;
  // var d = strSimilarity2Number(s, t);
  // return (1 - d / l).toFixed(4);
}

/**数组排序 */
export const sortArr = (arr) => {
  arr.sort((a,b) => {
    return a - b
  })
}


function termFreqMap(str) {
  var words = str.split(' ');
  var termFreq = {};
  words.forEach(function(w) {
      termFreq[w] = (termFreq[w] || 0) + 1;
  });
  return termFreq;
}

function addKeysToDict(map, dict) {
  for (var key in map) {
      dict[key] = true;
  }
}

function termFreqMapToVector(map, dict) {
  var termFreqVector = [];
  for (var term in dict) {
      termFreqVector.push(map[term] || 0);
  }
  return termFreqVector;
}

function vecDotProduct(vecA, vecB) {
  var product = 0;
  for (var i = 0; i < vecA.length; i++) {
      product += vecA[i] * vecB[i];
  }
  return product;
}

function vecMagnitude(vec) {
  var sum = 0;
  for (var i = 0; i < vec.length; i++) {
      sum += vec[i] * vec[i];
  }
  return Math.sqrt(sum);
}

function cosineSimilarity(vecA, vecB) {
  return vecDotProduct(vecA, vecB) / (vecMagnitude(vecA) * vecMagnitude(vecB));
}

export const Cosinesimilarity = (strA, strB) => {
  strA = (strA||'').toLocaleLowerCase().replace(/<[^>]+>/g, '').replace(/[^a-z0-9\s\\'\\’]+/g, '').replace(/\s+/g, ' ')
  strB = (strB||'').toLocaleLowerCase().replace(/<[^>]+>/g, '').replace(/[^a-z0-9\s\\'\\’]+/g, '').replace(/\s+/g, ' ')

  if(strA === '' || strB === '') return 0
  
  var termFreqA = termFreqMap(strA);
  var termFreqB = termFreqMap(strB);

  var dict = {};
  addKeysToDict(termFreqA, dict);
  addKeysToDict(termFreqB, dict);

  var termFreqVecA = termFreqMapToVector(termFreqA, dict);
  var termFreqVecB = termFreqMapToVector(termFreqB, dict);

  return cosineSimilarity(termFreqVecA, termFreqVecB) * 100;
}

export const textDiff_ = (strA, strB, articleType) => {
  // strA原文
  typeof strA == 'object' && (strA = strA.join(' \n ').replace(/(##)/g, " $1 ").replace(/(&&)/g, " $1 "))
  let ocount = strA.split(' ').filter((v)=>{return !!v}).length
  let dcount = 0
  let fullCount = 0
  let diffs = Diff.diffWords(strA, strB, {
    ignoreCase: true
  })
  console.log(555, strA, strB, diffs)
  let prevOp = '', curOp = ''
  let rs = [], tmpma = {}, tmpla = [], ns = []
  // console.log(diffs)
  for(let d of diffs){
    if  (d.added) {
      if (ns.indexOf(d.value) === -1) {
        ns.push(d.value)
      }
    }
  }
  for(let d of diffs){
    // console.log(d)
    tmpma = {}
    curOp = d.added ? 'add' : (d.removed ? 'removed' : '')
    // if (d.added) {
    //   curOp = 'add'
    // } else if (d.removed) {
    //   curOp = 'removed'
    // } else {
    //   curOp = ''
    // }
    console.log(curOp + '----============')
    tmpma.word = d.value
    if(prevOp == 'removed' && curOp == 'add'){//修改
      rs[rs.length-1].isColor = '#FF9D00'
    } else if(curOp === 'removed'){//删除
      tmpma.isColor = '#FD3462'
    }else if(curOp === 'add'){//添加
    // ns.push(d.value)
    }else if(curOp === ''){//无变化
      tmpma.isColor = '#11AA8E'
      dcount += d.value.split(' ').filter((v)=>{return !!v}).length
    }
    prevOp = curOp
    console.log(ns)
    if(tmpma.isColor){
      console.log(tmpma)
      rs.push(tmpma)
      for(let w of tmpma.word.split(' ')){
        if(w && !/^[\s|&&|##|\n]+$/.test(w)) {
          let color = ''
          let isDiff = false
            ns.map(elem => {
              if ((w.indexOf(elem) !== -1 || elem.indexOf(w) !== -1) && Math.abs(w.length - elem.length < 3)) {
                fullCount++
                isDiff = true
                return
              }
            })
        color = tmpma.isColor
        if (isDiff) {
          w = `${w}::#FF9D00`
        } else {
          w = `${w}::${color}`
        }
        
        }
        tmpla.push(w)
      }
    }
  }
  console.log(tmpla)
  tmpla = tmpla.join(' ').replace(/ (##) /g, "$1").replace(/ (&&) /g, "$1").split(' \n ')
  console.log(tmpla)
  
  let arr = []
  let headArr = []
  let endArr = []
  let head = ''
  let end = ''
  if (articleType === 1 || articleType === 5 || articleType === 2) {
    head = tmpla.splice(0,1)[0]
    console.log(head)
    end = tmpla.pop()
    console.log(end)
    let h = head.split(' ')
    let e = end.split(' ')
    h.map(n => {
      let obj = {}
      if (n.indexOf('&&') !== -1) {
        n = n.replace('&&', '<span style="margin-left: 40px;"></span>')
      } else if (n.indexOf('##') !== -1) {
        n = n.replace('##', '<span style="display: block;"></span>')
      }
      if (n.indexOf('::') !== -1) {
        let wordArr = n.split('::')
        obj.word = wordArr[0] + ' '
        if (wordArr[1].length > 7) {
          console.log(wordArr[1])
          let st = wordArr[1].substr(0,7)
          console.log(st)
          console.log('===============================')
          obj.isColor = st
          let obj1 = {}
          obj1.word = '<span style="display:block"></span>'
          headArr.push(obj)
          headArr.push(obj1)
        } else {
          console.log('没有')
          obj.isColor = wordArr[1]
          headArr.push(obj)
        }
      } else {
        obj.word = n + ' '
        headArr.push(obj)
      }
    })
    e.map(n => {
      let obj = {}
      if (n.indexOf('&&') !== -1) {
        n = n.replace('&&', '<span style="margin-left: 40px;"></span>')
      } else if (n.indexOf('##') !== -1) {
        n = n.replace('##', '<span style="display: block;"></span>')
      }
      if (n.indexOf('::') !== -1) {
        let wordArr = n.split('::')
        obj.word = wordArr[0] + '  '
        if (wordArr[1].length > 7) {
          console.log(wordArr[1])
          let st = wordArr[1].substr(0,7)
          console.log(st)
          console.log('===============================')
          obj.isColor = st
          let obj1 = {}
          obj1.word = '<span style="display:block"></span>'
          endArr.push(obj)
          endArr.push(obj1)
        } else {
          console.log('没有')
          obj.isColor = wordArr[1]
          endArr.push(obj)
        }
      } else {
        obj.word = n + '  '
        endArr.push(obj)
      }
    })
  } else if (articleType === 3 || articleType === 4) {
    head = tmpla.splice(0,1)[0]
    let e = head.split(' ')
    e.map(n => {
      let obj = {}
      if (n.indexOf('&&') !== -1) {
        n = n.replace('&&', '<span style="margin-left: 40px;"></span>')
      } else if (n.indexOf('##') !== -1) {
        n = n.replace('##', '<span style="display: block;"></span>')
      }
      if (n.indexOf('::') !== -1) {
        let wordArr = n.split('::')
        obj.word = wordArr[0] + '  '
        if (wordArr[1].length > 7) {
          console.log(wordArr[1])
          let st = wordArr[1].substr(0,7)
          console.log(st)
          console.log('===============================')
          obj.isColor = st
          let obj1 = {}
          obj1.word = '<span style="display:block"></span>'
          headArr.push(obj)
          headArr.push(obj1)
        } else {
          console.log('没有')
          obj.isColor = wordArr[1]
          headArr.push(obj)
        }
      } else {
        obj.word = n + '  '
        headArr.push(obj)
      }
    })
  }
  tmpla.map(item => {
    let elem = item.split(' ')
    elem.map(n => {
      let obj = {}
      if (n.indexOf('&&') !== -1) {
        n = n.replace('&&', '<span style="margin-left: 20px;"></span>')
      }
      else if (n.indexOf('##') !== -1) {
        n = n.replace('##', '<span style="display: block;"></span>')
      }
      if (n.indexOf('::') !== -1) {
        let wordArr = n.split('::')
        obj.word = wordArr[0] + '  '
       // obj.isColor = wordArr[1]
        if (wordArr[1].length > 7) {
          console.log(wordArr[1])
          let st = wordArr[1].substr(0,7)
          console.log(st)
          console.log('===============================')
          obj.isColor = st
          let obj1 = {}
          obj1.word = '<span style="display:block"></span>'
          arr.push(obj)
          arr.push(obj1)
        } else {
          console.log('没有')
          obj.isColor = wordArr[1]
          arr.push(obj)
        }
      } else {
        obj.word = n + '  '
        arr.push(obj)
      }
    })
  })
  // console.log(arr)
  console.log(ocount + '----' + dcount + '----' + (dcount + fullCount))
  return {
    otext: tmpla,
    text: arr,
    headArr: headArr,
    endArr: endArr,
    dcount: ((dcount / ocount) * 100).toFixed(2),
    full: (((dcount + fullCount) / ocount) * 100).toFixed(2)
  }
}

export const textDiff = (strA, strB) => {
  // strA原文
  typeof strA == 'object' && (strA = strA.join(' $$$$$ ').replace(/(##)/g, " $1 ").replace(/(&&)/g, " $1 "))
  // 去除转写里的符号
  strB = strB.replace(/[.,/#!$%^&*;:{}=\-_`~()]/gi, '')
  let ocount = strA.split(' ').filter((v)=>{return !!v}).length
  let dcount = 0
  let diffs = Diff.diffWords(strA, strB, {
    ignoreCase: true
  })
  console.log(555, strA, strB, diffs)

  let prevOp = '', curOp = ''
  let rs = [], tmpma = {}, tmpla = []
  // console.log('==================diffs', diffs)
  for(let d of diffs){
    tmpma = {}
    curOp = d.added ? 'add' : (d.removed ? 'removed' : '')
    tmpma.word = d.value
    if(prevOp == 'removed' && curOp == 'add'){//修改
      rs[rs.length-1].isColor = '#FF9D00'
      // console.log(rs[rs.length - 1], tmpma, tmpla, '-------')
    }else if(curOp == 'removed'){//删除
      tmpma.isColor = '#FD3462'
    }else if(curOp == 'add'){//添加
    }else if(curOp == ''){//无变化
      tmpma.isColor = '#11AA8E'
      dcount += d.value.split(' ').filter((v)=>{return !!v}).length
    }
    prevOp = curOp
    if(tmpma.isColor){
      rs.push(tmpma)
    }
  }
  // rs纠错
  if(rs[rs.length-1].isColor == '#FF9D00') rs[rs.length-1].isColor = '#FD3462'
  for(let r of rs){
    if(r.isColor){
      for(let w of r.word.split(' ')){
        if(w && !/^[\s|&&|##|\n|${5}]+$/.test(w)){
          w = `${w}::${r.isColor}`
        }
        tmpla.push(w)
      }
    }
  }
  
  // console.log('rs =============++>' , rs)
  // console.log(77777, tmpla.join(' ').replace(/(##)/g, "$1").replace(/(&&)/g, "$1"), '========2222')
  // tmpla = tmpla.join(' ').replace(/(##)/g, '$1 \n').replace(/(##)/g, "$1").replace(/(&&)/g, "$1").split(' \n ')
  // console.log(77777, tmpla.join(' '), tmpla.join(' ').replace(/ (##) /g, "$1").replace(/ (&&) /g, "$1").split(' $$$$$ '), '========2222')
  tmpla = tmpla.join(' ').replace(/ (##) /g, "$1").replace(/ (&&) /g, "$1").split(' $$$$$ ')
  // console.log(tmpla, '------tmpla------')
  // 三度处理
  let tmpa = 0, tmpb = 0, tmpc = 0, tmpd = 0
  let tmpe = 0, tmpf = 0, tmpg = 0, tmph = 0
  let centens = tmpla.filter((v)=>{return !!v})
  for(let cen of centens){
    cen = cen.split(' ').filter((v)=>{return !!v})
    tmpa = 0, tmpb = 0, tmpc = 0, tmpd = 0
    for(let word of cen){
      word = word.split('::')
      if(!word[1]) continue
      tmph += 1
      tmpd += 1
      word[1] == '#11AA8E' && (tmpa += 1) && (tmpg += 1)
      word[1] == '#FF9D00' && (tmpb += 1) && (tmpg += 0.6)
      word[1] == '#FD3462' && (tmpc += 1)
    }
    // 每句正确率
    tmpe = Math.floor((tmpa+tmpb)/tmpd*100)
    if(tmpe >= 40) tmpf += 1
  }
  let rtn = {
    otext: tmpla,
    text: rs,
    full: ((tmpf / centens.length) * 100).toFixed(2),
    correct: ((tmpg / tmph) * 100).toFixed(2)
  }
  // console.log(8888, strA, '----', strB, '----', rtn, dcount,  ocount, '-=---------')
  return rtn
}

const arr2ColorTextHtmlObj = (arr) => {
   let resultArr = arr.map(v => {
    let sentence = v.split(' ')
    return sentence.map(word => {
      let wordArr = word.split('::')
      return {
        word: wordArr[0],
        isColor: (wordArr[1] || '').replace('##', '')
      }
    })
  })
  return _.flatten(resultArr)
}

export const textFormatArticl = (text, articleType) => {
  text = text.map((v)=>{
    v = v.replace(/(##|&&)/g, ' $1 ')
    return v
  })
  console.log(3333, text, articleType,  '---------text')
  text = _.cloneDeep(text)
  let Obj = {
    headArr: [],
    text: [],
    endArr: []
  }
  if ([1, 2, 5].includes(+articleType)) {
    Obj.headArr = arr2ColorTextHtmlObj(text.splice(0, 1))
    // if (+articleType === 1 || +articleType === 5) {
    //   // 书信 邮件取后两个
    //   Obj.endArr = _.flatten(arr2ColorTextHtmlObj(text.splice(-2, 2)))
    // } else {
      Obj.endArr = arr2ColorTextHtmlObj(text.splice(-1, 1))
    // }
    Obj.text = arr2ColorTextHtmlObj(text)
  } else if ([3, 4].includes(articleType)) {
    Obj.headArr = arr2ColorTextHtmlObj(text.splice(0, 1))
    Obj.text = arr2ColorTextHtmlObj(text)
  } else {
    Obj.text = arr2ColorTextHtmlObj(text)
  }
  console.log(Obj, '---------text')

  return Obj
}

// let a = ["Dear Nick,", "&&How's everything going?##", "&&Our school is holding an English reading festival this June.", "I'm very interested in it. ", "There are many different activities in the festival such as reading good English books, sharing good stories and so on. ", "It's a good chance for us to learn more about western cultures. ", "However, I have some problems. ", "First, I don't have enough books. ", "For example, I want to get some books about western history. ", "Next, I'm not so good at English, I have trouble in reading.  ", "Would you please share some good books with me and give me some advice on reading?##", "&&I expect to hear from you soon. ##", "&&Best wishes!##", "Yours,##Li Hua "]
// console.log(666, textDiff(a, `Dear Nico hi is everything going our school is holding an English writing festival this soon I am very interested in it There are many different activities in the festival such as Letting good English books sharing good stories and so on he is a good chance for us to learn more about western cultures However I have some problems First I don't have enough books For example I want to get some books about western history Nest I'm not so good at English I have trouble reading would you please share some good books with me and give me some advice on reading? Is packed to hear from you soon best wishes yaar`))
